<script setup lang="ts">
import { reactive, ref, watchEffect } from 'vue';
import { useRouter } from 'vue-router';

import { useUserStore } from '@vben/stores';

import { message } from 'ant-design-vue';

import { sendSmsCodeApi, updatePasswordApi } from '#/api/core/auth';
import { useAuthStore } from '#/store';

defineOptions({ name: 'AccountChangePassword' });

const router = useRouter();
const userStore = useUserStore();
const authStore = useAuthStore();

const form = reactive({
  mobile: '',
  oldPassword: '',
  code: '',
  password: '',
  confirmPassword: '',
});

const sendingCode = ref(false);
const showPassword = ref(false);
const showConfirmPassword = ref(false);
const countdown = ref(0);
const submitting = ref(false);
const isSuccess = ref(false);
let timer: null | number = null;

watchEffect(() => {
  form.mobile = userStore.userInfo?.phone ?? '';
});

function startCountdown() {
  countdown.value = 60;
  timer = window.setInterval(() => {
    countdown.value -= 1;
    if (countdown.value <= 0 && timer) {
      window.clearInterval(timer);
      timer = null;
    }
  }, 1000);
}

async function handleSendCode() {
  if (countdown.value > 0 || sendingCode.value) {
    return;
  }
  sendingCode.value = true;
  try {
    if (!form.mobile) {
      throw new Error('未找到绑定的手机号');
    }
    await sendSmsCodeApi({
      mobile: form.mobile,
      smsmode: 2,
    });
    message.success('验证码已发送，请查收短信');
    startCountdown();
  } catch (error: any) {
    console.error('发送验证码失败:', error);
    message.error(error?.message || '发送验证码失败，请稍后重试');
  } finally {
    sendingCode.value = false;
  }
}

function validateForm() {
  if (!form.oldPassword) {
    message.warning('请输入旧密码');
    return false;
  }
  if (!form.code) {
    message.warning('请输入验证码');
    return false;
  }
  if (!form.password || form.password.length < 6) {
    message.warning('请输入至少6位的新密码');
    return false;
  }
  if (form.password !== form.confirmPassword) {
    message.warning('两次输入的密码不一致');
    return false;
  }
  return true;
}

async function handleSubmit() {
  if (!validateForm()) {
    return;
  }
  submitting.value = true;
  try {
    await updatePasswordApi({
      oldPassword: form.oldPassword,
      newPassword: form.password,
      code: form.code,
    });
    message.success('修改密码成功，请重新登录');
    isSuccess.value = true;
  } catch (error: any) {
    console.error('修改密码失败:', error);
    message.error(
      error?.response?.data?.message ||
        error?.message ||
        '修改密码失败，请稍后重试',
    );
  } finally {
    submitting.value = false;
  }
}

function handleCancel() {
  router.back();
}

function togglePasswordVisible(target: 'confirm' | 'password') {
  if (target === 'password') {
    showPassword.value = !showPassword.value;
  } else {
    showConfirmPassword.value = !showConfirmPassword.value;
  }
}

async function handleGoLogin() {
  await authStore.logout(true);
}
</script>

<template>
  <div class="min-h-[calc(100vh-120px)] bg-[#f7f3ee] py-10">
    <div
      class="mx-auto w-full max-w-3xl rounded-2xl border border-[#f0d7b2] bg-white p-10 shadow-[0_12px_40px_rgba(237,200,162,0.3)]"
    >
      <template v-if="isSuccess">
        <h1 class="mb-14 text-2xl font-semibold text-[#5d412b]">修改密码</h1>
        <div class="flex flex-col items-center justify-center space-y-6 py-16">
          <div
            class="flex h-20 w-20 items-center justify-center rounded-full bg-[#e6f7e7]"
          >
            <span class="text-4xl">✔️</span>
          </div>
          <div class="text-center">
            <h2 class="text-xl font-semibold text-[#5d412b]">修改密码成功</h2>
            <p class="mt-2 text-sm text-[#8c8885]">修改密码成功，请重新登录</p>
          </div>
          <button
            type="button"
            class="rounded-full bg-[#d6a15f] px-10 py-3 text-sm font-medium text-white transition-colors hover:bg-[#c9904b]"
            @click="handleGoLogin"
          >
            返回登录界面
          </button>
        </div>
      </template>
      <template v-else>
        <h1 class="mb-8 text-2xl font-semibold text-[#5d412b]">修改密码</h1>

        <div class="space-y-6">
          <label class="flex flex-col space-y-2">
            <span class="text-sm text-[#a87c4f]">旧密码</span>
            <input
              v-model="form.oldPassword"
              :type="showPassword ? 'text' : 'password'"
              placeholder="输入旧密码"
              class="w-full rounded-lg border border-[#f2c998] px-4 py-3 text-sm text-[#5d412b] placeholder-[#d1b494] focus:border-[#d6b184] focus:outline-none focus:ring-2 focus:ring-[#f8dfc3]"
            />
          </label>

          <label class="flex flex-col space-y-2">
            <span class="text-sm text-[#a87c4f]">手机号</span>
            <input
              v-model="form.mobile"
              type="tel"
              disabled
              class="cursor-not-allowed rounded-lg border border-[#f2c998] bg-[#fdf7ef] px-4 py-3 text-sm text-[#5d412b] placeholder-[#d1b494]"
            />
          </label>

          <label class="flex flex-col space-y-2">
            <span class="text-sm text-[#a87c4f]">验证码</span>
            <div class="flex items-center space-x-4">
              <input
                v-model="form.code"
                type="text"
                maxlength="6"
                placeholder="短信验证码"
                class="flex-1 rounded-lg border border-[#f2c998] px-4 py-3 text-sm text-[#5d412b] placeholder-[#d1b494] focus:border-[#d6b184] focus:outline-none focus:ring-2 focus:ring-[#f8dfc3]"
              />
              <button
                type="button"
                class="rounded-full border border-[#f2c998] px-5 py-2 text-sm text-[#d6a15f] transition-colors hover:border-[#d6a15f] hover:bg-[#fdf2e3] disabled:cursor-not-allowed disabled:border-[#f2c998] disabled:text-[#d1b494]"
                :disabled="countdown > 0 || sendingCode"
                @click="handleSendCode"
              >
                {{
                  countdown > 0
                    ? `${countdown}s 后重试`
                    : sendingCode
                      ? '发送中...'
                      : '发送验证码'
                }}
              </button>
            </div>
          </label>

          <label class="flex flex-col space-y-2">
            <span class="text-sm text-[#a87c4f]">新密码</span>
            <div class="relative">
              <input
                v-model="form.password"
                :type="showPassword ? 'text' : 'password'"
                placeholder="输入6-20位密码"
                class="w-full rounded-lg border border-[#f2c998] px-4 py-3 pr-12 text-sm text-[#5d412b] placeholder-[#d1b494] focus:border-[#d6b184] focus:outline-none focus:ring-2 focus:ring-[#f8dfc3]"
              />
              <button
                type="button"
                class="absolute inset-y-0 right-0 flex items-center px-4 text-[#d6a15f] transition-colors hover:text-[#c0904d]"
                @click="togglePasswordVisible('password')"
              >
                {{ showPassword ? '🙈' : '👁' }}
              </button>
            </div>
          </label>

          <label class="flex flex-col space-y-2">
            <span class="text-sm text-[#a87c4f]">再次输入</span>
            <div class="relative">
              <input
                v-model="form.confirmPassword"
                :type="showConfirmPassword ? 'text' : 'password'"
                placeholder="确认密码"
                class="w-full rounded-lg border border-[#f2c998] px-4 py-3 pr-12 text-sm text-[#5d412b] placeholder-[#d1b494] focus:border-[#d6b184] focus:outline-none focus:ring-2 focus:ring-[#f8dfc3]"
              />
              <button
                type="button"
                class="absolute inset-y-0 right-0 flex items-center px-4 text-[#d6a15f] transition-colors hover:text-[#c0904d]"
                @click="togglePasswordVisible('confirm')"
              >
                {{ showConfirmPassword ? '🙈' : '👁' }}
              </button>
            </div>
          </label>
        </div>

        <div class="mt-12 flex justify-end space-x-4">
          <button
            type="button"
            class="rounded-full bg-[#d6d1cd] px-8 py-3 text-sm font-medium text-[#6f6c69] transition-colors hover:bg-[#c7c1bc]"
            @click="handleCancel"
          >
            取消
          </button>
          <button
            type="button"
            class="rounded-full bg-[#d6a15f] px-8 py-3 text-sm font-medium text-white transition-colors hover:bg-[#c9904b] disabled:cursor-not-allowed disabled:bg-[#e3c4a0]"
            :disabled="submitting"
            @click="handleSubmit"
          >
            {{ submitting ? '提交中...' : '保存资料' }}
          </button>
        </div>
      </template>
    </div>
  </div>
</template>
